package com.apes.autoparts.searcher.vin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.searcher.DataSource;
import com.apes.autoparts.searcher.repository.AutopartsDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class InnerProductsSearcher<T, R> implements ProductsSearcher<T, R> {

    @Autowired
    AutopartsDao autopartsDao;

    @Override
    public R parse(T element) {

        return (R) element;
    }

    @Override
    public String[] getSource() {
        return new String[]{DataSource.INNER.name()};
    }




    public JSONObject getProducts(JSONObject param) {
        JSONObject returnJson = new JSONObject();
        JSONArray partNumbers = param.getJSONArray("partNumbers");

        partNumbers.stream().forEach(json -> {
            JSONObject tempJson = (JSONObject) json;
            // 匹配参数 partnumber pjmcid
            if( tempJson.getString("PARTNUMBER") != null && tempJson.getString("PJMCID") != null ){
                JSONArray productArray = autopartsDao.getProduct(tempJson);
                tempJson.put("products", productArray);
            } else {
                //TODO: 没有配件名称的推送代办
                tempJson.put("products", new JSONArray());
            }
        });

        returnJson.put("dataSource", param.getString("dataSource"));
        returnJson.put("data", partNumbers);

        return returnJson;
    }
}
